//
//  KDMSettingController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/3.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDMSettingController.h"
#import "KDKeywordSetController.h"
#import "KDWebSetController.h"
#import "KDAuthorSetController.h"
#import "KDWeiboSetController.h"
#import "KDMSettingCell.h"
#import "KDMSettingCellModel.h"
#import "KDWebSetController.h"
#import "KDWebBlockSetController.h"
#import "KDMonitorRequestTool.h"
#import "KDMGetSetUpListParam.h"
#import "KDMGetWeiboListResult.h"
#import "KDMGetWebListResult.h"
#import "KDMGetAuthorListResult.h"
#import "KDMGetKeyWordListResult.h"
#import "KDMDeleteParam.h"
#import "SVProgressHUD.h"
#define NAVIGATION_HEIGHT 100
@interface KDMSettingController ()<UITableViewDelegate, UITableViewDataSource, KDMSettingCellDelegate, KDKeywordSetControllerDelegate>
/**
 *  自定义的导航栏
 */
@property (nonatomic, weak) UIView *navigationbar;
@property (nonatomic, strong) NSArray *infoArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString * page;

@end

@implementation KDMSettingController

#pragma mark - 板块设置区
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
    [self setUpNavgationbar];
    self.page = @"1";
    [self setUpTableView];
}
- (void)setUpNavgationbar{
    UIView *navigationbar = [[UIView alloc]initWithFrame:CGRectMake(0, 20, screenW, NAVIGATION_HEIGHT)];
    self.navigationbar = navigationbar;
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, 0, 168, 92);
    addBtn.centerX = self.navigationbar.centerX;
    addBtn.highlighted = NO;
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationbar addSubview:addBtn];
    switch (self.mainType) {
        case 0:{
            navigationbar.backgroundColor = WQColor(85, 196, 95);
            UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
            statusBarView.backgroundColor=WQColor(85, 196, 95);
            [self.navigationController.view addSubview:statusBarView];
            [addBtn setImage:[UIImage imageNamed:@"添加关键字主题"] forState:UIControlStateNormal];
            [addBtn setImage:[UIImage imageNamed:@"添加关键字主题"] forState:UIControlStateHighlighted];

            break;
        }
        case 1:{
            navigationbar.backgroundColor = WQColor(255, 150, 65);;
            UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
            statusBarView.backgroundColor=WQColor(255, 150, 65);;
            [self.navigationController.view addSubview:statusBarView];
            [addBtn setImage:[UIImage imageNamed:@"添加网站主题"] forState:UIControlStateNormal];
            [addBtn setImage:[UIImage imageNamed:@"添加网站主题"] forState:UIControlStateHighlighted];

            break;
        }
        case 2:{
            navigationbar.backgroundColor = WQColor(83, 198, 255);
            UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
            statusBarView.backgroundColor=WQColor(83, 198, 255);
            [self.navigationController.view addSubview:statusBarView];
            [addBtn setImage:[UIImage imageNamed:@"添加作者监测"] forState:UIControlStateNormal];
            [addBtn setImage:[UIImage imageNamed:@"添加作者监测"] forState:UIControlStateHighlighted];

            break;
        }
        case 3:{
            navigationbar.backgroundColor = WQColor(254, 79, 87);
            UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
            statusBarView.backgroundColor=WQColor(254, 79, 87);
            [self.navigationController.view addSubview:statusBarView];
            [addBtn setImage:[UIImage imageNamed:@"添加微博监测"] forState:UIControlStateNormal];
            [addBtn setImage:[UIImage imageNamed:@"添加微博监测"] forState:UIControlStateHighlighted];

            break;
        }
        default:
            break;
    }
    
    [self setUpBackBtn];
//    [self setUpAddBtn];
    [self.view addSubview:navigationbar];
}

- (void)setUpBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"leftArrow"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 35, 35);
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationbar addSubview:backBtn];
}
- (void)setUpTableView{
    CGFloat y = CGRectGetMaxY(self.navigationbar.frame);
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , y, screenW, screenH - y) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    if (self.mainType) {
        tableView.rowHeight = 145;
    }else{
        tableView.rowHeight = 175;;
    }
    //    if (self.themeArr.count == 0) {
    //        KDHomeThemeModel *model = [[KDHomeThemeModel alloc]init];
    //        model.parentid = 1;
    //        model.ID = 0;
    //        self.homeThemeModel = model;
    //    }else{
    //        self.homeThemeModel = self.themeArr[0];
    //    }
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    tableView.footer = footer;
    [tableView.header beginRefreshing];
    [self.view addSubview:tableView];
    

}
#pragma mark - 事件点击区
/**
 *  返回按钮被点击了
 */
- (void)backBtnClick{
    if (_delegate && [_delegate respondsToSelector:@selector(KDMSettingController:backBtnClickWithMainType:)]) {
        [_delegate KDMSettingController:self backBtnClickWithMainType:self.mainType];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  添加按钮被点击了
 */
- (void)addBtnClick{
    self.navigationController.navigationBar.hidden = NO;
    self.hidesBottomBarWhenPushed = YES;
    switch (self.mainType) {
        case 0://进入关键字添加
        {
            KDKeywordSetController *keyword = [[KDKeywordSetController alloc]init];
            keyword.add = YES;//表示是用于添加
            keyword.delegate = self;
            [self.navigationController pushViewController:keyword animated:YES];
            break;
        }
        case 1://进入网站添加
        {
            KDWebSetController*web = [[KDWebSetController alloc]initWithNibName:@"KDWebSetController" bundle:nil];
            [self.navigationController pushViewController:web animated:YES];
            break;
        }
        case 2://进入作者添加
        {
            KDAuthorSetController *author = [[KDAuthorSetController alloc]init];
            author.type = @"add";
            [self.navigationController pushViewController:author animated:YES];
            break;
        }
        case 3://进入微博添加
        {
            KDWeiboSetController *weibo = [[KDWeiboSetController alloc]init];
            weibo.type = @"add";
            [self.navigationController pushViewController:weibo animated:YES];
            break;
        }
        default:
            break;
    }
}



#pragma mark - 网络加载区
//- (void)getFakeData
//{
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"FakeData1" ofType:@"plist"];
//    //    NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistPath];
//    self.infoArr = [KDMSettingCellModel objectArrayWithFile:plistPath];
//}
- (KDMGetSetUpListParam *)getParam{
    KDMGetSetUpListParam *param = [[KDMGetSetUpListParam alloc]init];
    param.limit = @"20";
        switch (self.mainType) {
        case 0:
            param.method = @"getMonitorKeywordSettingList";
            
            break;
        case 1:
            param.method = @"getMonitorWebSiteSettingList";
//            param.page = @"1";
            break;
        case 2:
            param.method = @"getMonitorAuthorSettingList";
            break;
//        case 3:
//            param.method = @"weiboMonitorSetup";
//            break;
        default:
            break;
    }
    return param;
}
- (void)loadData{
    WS(ws);
    self.page = @"1";
    KDMGetSetUpListParam *param = [self getParam];
    param.p = self.page;
        [KDMonitorRequestTool getSetUpListWithParam:param WithMainType:self.mainType success:^(KDBaseResult *  responseObejct) {
        if ([responseObejct.status isEqualToString:@"notlogin"]) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
        }else{
            ws.infoArr = responseObejct.info;
//            switch (ws.mainType) {
//                case 0:{
//                    KDMGetKeyWordListResult *result = (KDMGetKeyWordListResult *)responseObejct;
//                    ws.infoArr =  result.info;
//                    break;
//                }
//                    
//                case 1:{
//                    KDMGetWebListResult *result = (KDMGetWebListResult *)responseObejct;
//                    ws.infoArr =  result.info;
//                    break;
//                }
//                case 2:{
//                    KDMGetAuthorListResult *result = (KDMGetAuthorListResult *)responseObejct;
//                    ws.infoArr =  result.info;
//                    break;
//                }
//                default:
//                    break;
//            }
            [ws.tableView reloadData];
            [ws.tableView.header endRefreshing];
            [ws.tableView.footer resetNoMoreData];
        }
        
    } failure:^(NSError *error) {
        [ws.tableView.header endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
- (void)loadMoreData{
    WS(ws);
    KDMGetSetUpListParam *param = [self getParam];
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    param.p = self.page;
    [KDMonitorRequestTool getSetUpListWithParam:param WithMainType:self.mainType success:^(KDBaseResult * responseObejct) {
        
        if (responseObejct.count <= self.infoArr.count) {//判断是不是加载完了
            [ws.tableView.footer endRefreshing];
            return ;
        }
        NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
        [arr addObjectsFromArray: responseObejct.info];
//        switch (ws.mainType) {
//            case 0:{
//                
//                KDMGetKeyWordListResult *result = (KDMGetKeyWordListResult *)responseObejct;
//                [arr addObjectsFromArray: result.info];
//                ws.infoArr =  result.info;
//                break;
//            }
//                
//            case 1:{
//                KDMGetWebListResult *result = (KDMGetWebListResult *)responseObejct;
//                [arr addObjectsFromArray: responseObejct.info];
//                ws.infoArr =  result.info;
//                break;
//            }
//            case 2:{
//                KDMGetAuthorListResult *result = (KDMGetAuthorListResult *)responseObejct;
//                [arr addObjectsFromArray: result.info];
//                ws.infoArr =  result.info;
//                break;
//            }
//            case 3:{
//                KDMGetWeiboListResult *result = (KDMGetWeiboListResult *)responseObejct;
//                [arr addObjectsFromArray: result.info];
//                ws.infoArr =  result.info;
//                break;
//            }
//            default:
//                break;
//        }
        
        ws.infoArr = arr;
        [ws.tableView reloadData];
        [ws.tableView.footer endRefreshing];
        
    } failure:^(NSError *error) {
        [ws.tableView.footer endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
/**
 *  删除的网络请求
 */
- (void)deleteRequestWithModel:(KDMSettingCellModel *)model{
    WS(ws);
    KDMDeleteParam *param = [[KDMDeleteParam alloc]init];
    switch (self.mainType) {
        case 0:
            param.method = @"delMonitorKeywordSetting";
            param.m_Id = model.m_Id;
            
            break;
        case 1:
            param.method = @"delMonitorWebSite";
            param.wsm_id = model.m_Id;
            break;
        case 2:
            param.method = @"delAuthorMonitorSetting";
            param.a_id =  model.m_Id;
            param.u_id = [NSString stringWithFormat:@"%ld", model.UID];
            break;
        default:
            break;
    }
    
    [KDMonitorRequestTool deleteMonitorWithParam: param WithMainType:self.mainType success:^(KDBaseResult *responseObejct) {
//        KDLog(@"%@",responseObejct.info);
        if ([responseObejct.status isEqualToString:@"ok"]) {//如果请求成功了久开始减
            NSMutableArray *tempArr = [NSMutableArray arrayWithArray:ws.infoArr];
            for (KDBaesMonitorModel *model1 in ws.infoArr) {
                if (model1.m_Id == model.m_Id) {
                    [tempArr removeObject:model1];
                    break;
                }
            }
            ws.infoArr = tempArr;
            [ws.tableView reloadData];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDMSettingCell *cell = [KDMSettingCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            KDMSettingCellModel *model = self.infoArr[indexPath.row];
            model.mainType = [NSString stringWithFormat:@"%ld", self.mainType];
            cell.model = model;
        }
    return cell;
}

//- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (self.mainType) {
//        return 145;
//    }else{
//        return 175;
//    }
//    
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (self.mainType) {
//        return 145;
//    }else{
//        return 175;
//    }
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - KDMSettingCellDelegate
/**
 *  编辑按钮被点击了
 */
- (void)KDMSettingCell:(KDMSettingCell *)cell editBtnClickWithModel:(KDMSettingCellModel *)model{
    
    self.navigationController.navigationBar.hidden = NO;
    self.hidesBottomBarWhenPushed = YES;
    switch (_mainType) {
        case 0://进入关键字编辑
        {
            KDKeywordSetController *keyword = [[KDKeywordSetController alloc]init];
            keyword.delegate = self;
            keyword.model = model;
            keyword.add = NO;//表示是去编辑
            [self.navigationController pushViewController:keyword animated:YES];
            break;
        }
        case 1://进入网站编辑
        {
            KDWebBlockSetController *web = [[KDWebBlockSetController alloc]init];
            web.model = model;
            [self.navigationController pushViewController:web animated:YES];
            break;
        }
        case 2://进入作者编辑
        {
            KDAuthorSetController *author = [[KDAuthorSetController alloc]init];
            author.type = @"edit";
            author.model = model;
            [self.navigationController pushViewController:author animated:YES];
            break;
        }
        case 3://进入微博编辑
        {
            KDWeiboSetController *weibo = [[KDWeiboSetController alloc]init];
            weibo.type = @"edit";
            weibo.model = model;
            [self.navigationController pushViewController:weibo animated:YES];
            break;
        }
        default:
            break;
    }
    [self.tableView.header beginRefreshing];
}
- (void)KDMSettingCell:(KDMSettingCell *)cell deleteBtnClickWithModel:(KDMSettingCellModel *)model{
    
    NSInteger u_id;
    if (self.mainType == 2) {
        u_id = model.UID;
    }else{
        u_id = model.u_Id;
    }
    KDAccount *account = [KDAccountTool account];
    if (account.userId != u_id) {
        [SVProgressHUD showErrorWithStatus:@"非本人添加不可删除！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    [self deleteRequestWithModel:model];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //只在本控制器隐藏
    self.navigationController.navigationBar.hidden = YES;
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    [self.navigationController.view addSubview:statusBarView];
    switch (self.mainType) {
        case 0:{
            statusBarView.backgroundColor=WQColor(85, 196, 95);
            break;
        }
        case 1:{
            statusBarView.backgroundColor=WQColor(255, 150, 65);;
            break;
        }
        case 2:{
            statusBarView.backgroundColor=WQColor(83, 198, 255);
            break;
        }
        case 3:{
            statusBarView.backgroundColor=WQColor(254, 79, 87);
            break;
        }
        default:
            break;
    }
    [self.tableView.header beginRefreshing];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    statusBarView.backgroundColor= KDColor;
    [self.navigationController.view addSubview:statusBarView];

}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
                break;
            default:
                break;
        }
    }
}
@end
